<template>
  <a-card :bordered="false">
    <div>
      <a-table
        ref="table"
        bordered
        size="small"
        rowKey="id"
        :scroll="{ x:width, y: height }"
        :customRow="onClickRowMulti"
        :columns="columns"
        :childrenColumnName="childrenColumnName"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: selectMode }"
        @expand="handleExpand"
        @change="handleTableChange">
      </a-table>
    </div>
  </a-card>
</template>

<script>
import { filterObj } from '@/utils/util'
import { getAction,postAction } from '@api/manage'


export default {
  name: "ChooseTable",
  components: {
  },
  props: {
    childrenColumnName: {
      type: String,
      default: function() {
        return 'children'
      },
    },
    width: {
      type: Number,
      default: function() {
        return null
      },
    },
    height: {
      type: Number,
      default: function() {
        return null
      },
    },
    source: {
      type: String,
      default: function() {
        return ''
      },
    },
    tableFields: {
      type: Array,
      default: function() {
        return []
      }
    },
    mode: {
      type: String,
      default: function() {
        return 'radio'
      }
    },
    rows: {
      type: Array,
      default: function() {
        return []
      }
    }
    // filter: {
    //   type: Boolean,
    //   default: function() {
    //     return false
    //   }
    // },
    // filterCondition: {
    //   type: Array,
    //   default: function() {
    //     return []
    //   }
    // }
  },
  watch: {
    source: function(newVal) {
      this.url = newVal
    },
    tableFields: function(newVal) {
      this.columns = newVal
    },
    mode: function(newVal) {
      this.selectMode = newVal
    },
    rows: function(newVal) {
      this.dataSource = newVal?newVal:[]
    }
  },
  data () {
    return {
      description: '通用选择列表',
      queryParam: {},
      url: this.source,
      selectMode: this.mode,
      dataSource: this.rows?this.rows:[],
      columns: this.tableFields,
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      isorter: {
        column: 'createTime',
        order: 'desc',
      },
      loading: false,
      selectedRowKeys: [],
      selectedRows: [],
      toggleSearchStatus: false
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    loadData(arg) {
      if(arg===1){
        this.ipagination.current = 1;
      }
      let params = this.getQueryParams();//查询条件
      console.log(params)
      this.loading = true
      this.onClearSelected()
      postAction(this.url, params).then((res)=>{
        if(res.success){
          if(res.result.records) {
            this.dataSource = res.result.records;
            this.ipagination.total = res.result.total;
          } else {
            this.dataSource = res.result
          }
          this.dataSource.forEach(item => {
            if(item.hasOwnProperty("isLeaf")) {
              this.checkIsLeaf(item)
            }
          })
        }
        this.$emit('beforeLoaded',this.dataSource)
        this.loading = false
      })
    },
    getQueryParams(){
      let param = Object.assign({}, this.queryParam,this.isorter);
      param.field = this.getQueryField();
      param.current = this.ipagination.current;
      param.size = this.ipagination.pageSize;
      return filterObj(param);
    },
    getQueryField(){
      let str = "id,";
      for(let a = 0;a<this.columns.length;a++){
        str+=","+this.columns[a].dataIndex;
      }
      return str;
    },
    onSelectChange (selectedRowKeys,selectionRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectionRows
    },
    onClearSelected(){
      this.selectedRowKeys = [];
      this.selectedRows = [];
    },
    searchByQuery(queryParam){
      this.queryParam = queryParam
      this.loadData(1)
    },
    searchReset(){
      let that = this;
      Object.keys(that.queryParam).forEach(function(key){
        that.queryParam[key] = '';
      });
      that.loadData(1);
    },
    handleTableChange(pagination, filters, sorter){
      //TODO 筛选
      if (Object.keys(sorter).length>0){
        this.isorter.column = sorter.field;
        this.isorter.order = "ascend"==sorter.order?"asc":"desc"
      }
      this.ipagination = pagination;
      this.loadData();
    },
    clearData() {
      this.queryParam = {}
      this.dataSource = []
      this.selectedRowKeys = []
      this.selectedRows = []
      this.ipagination.pageSize = 10
      this.ipagination.current = 1
    },
    checkIsLeaf(item) {
      if(item.hasOwnProperty('isLeaf')){
        if(item.isLeaf === 0){
          //非叶子节点懒加载的情况
          if(!item.children) {
            item.children = []
          }
        } else if (item.isLeaf === 1) {
          //将叶子节点children空数组置换为null
          item.children = null
        }
      }else{
        if(item.children && item.children.length === 0) {
          item.children = null
        }
      }
    },
    handleExpand(expanded, record) {
      if(record.children.length === 0) {
        this.loading = true
        getAction(this.url, { id: record.id }).then(res => {
          if(res.success){
            res.result.forEach(item => {
              this.checkIsLeaf(item)
              record.children.push(item)
            })
          }
          this.loading = false
        })
      } else {
        //针对叶子节点children为空数组的情况
        record.children.forEach(item => {
          this.checkIsLeaf(item)
        })
      }
    },
    onClickRowMulti(record) {
      if(this.selectMode === 'radio') {
        return {
          on: {
            click: () => {
              let rowKeys = this.selectedRowKeys
              if(rowKeys.length>0 && rowKeys.includes(record.id)){
                this.selectedRows.splice(0,1)
                rowKeys.splice(0,1)
              }else{
                this.selectedRows.splice(0,1)
                rowKeys.splice(0,1)
                this.selectedRows.push(record)
                rowKeys.push(record.id)
              }
              this.selectedRowKeys = rowKeys;
            },
            dblclick: (e) => {
              this.$emit("dbclick", record, e)
            }
          }
        }
      } else {
        return {
          on: {
            click: () => {
              let rowKeys=this.selectedRowKeys
              if(rowKeys.length>0 && rowKeys.includes(record.id)){
                this.selectedRows.splice(rowKeys.indexOf(record.id),1)
                rowKeys.splice(rowKeys.indexOf(record.id),1)
              }else{
                this.selectedRows.push(record)
                rowKeys.push(record.id)
              }
              this.selectedRowKeys = rowKeys;
            },
            dblclick: (e) => {
              this.$emit("dbclick", record, e)
            }
          }
        }
      }
    }
  }

}
</script>
<style scoped>

</style>